<template>
  <view class="container">
    <u-navbar
      title="绑定学生信息"
      :is-back="true"
    ></u-navbar>
    
    <view class="form-section">
      <u-form :model="formData" ref="uForm" :error-type="['message']">
        <u-form-item
          label="学校"
          prop="schoolId"
          required
          :border-bottom="true"
        >
          <view class="input-wrapper" @click="showSchoolPicker = true">
            <text v-if="formData.schoolName">{{ formData.schoolName }}</text>
            <text v-else class="placeholder">请选择学校</text>
            <u-icon name="arrow-right" size="24" color="#999"></u-icon>
          </view>
        </u-form-item>
        
        <u-form-item
          label="学号"
          prop="studentId"
          required
          :border-bottom="true"
        >
          <u-input
            v-model="formData.studentId"
            placeholder="请输入学号"
            type="text"
          />
        </u-form-item>
        
        <u-form-item
          label="姓名"
          prop="name"
          required
          :border-bottom="true"
        >
          <u-input
            v-model="formData.name"
            placeholder="请输入姓名"
            type="text"
          />
        </u-form-item>
        
        <u-form-item
          label="身份证号"
          prop="idCard"
          required
          :border-bottom="true"
        >
          <u-input
            v-model="formData.idCard"
            placeholder="请输入身份证号"
            type="idcard"
          />
        </u-form-item>
      </u-form>
      
      <view class="tips">
        <text>提示：请确保填写的信息准确无误，信息将用于身份验证</text>
      </view>
      
      <view class="submit-btn">
        <u-button type="primary" @click="submit">提交绑定</u-button>
      </view>
    </view>
    
    <!-- 学校选择器 -->
    <u-picker
      :show="showSchoolPicker"
      :columns="[schoolOptions]"
      @confirm="confirmSchool"
      @cancel="showSchoolPicker = false"
    ></u-picker>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      formData: {
        schoolId: '',
        schoolName: '',
        studentId: '',
        name: '',
        idCard: ''
      },
      schoolOptions: [],
      showSchoolPicker: false,
      rules: {
        schoolId: [
          { required: true, message: '请选择学校', trigger: 'change' }
        ],
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { min: 5, max: 20, message: '学号长度在5-20个字符之间', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              // 简单的身份证号验证
              const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
              return reg.test(value)
            }, 
            message: '身份证号格式不正确', 
            trigger: 'blur' 
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'hasLogin'])
  },
  onLoad() {
    this.getSchools()
    this.setRules()
    
    // 如果已经绑定了学生信息，则预填表单
    if (this.userInfo.studentInfo) {
      this.formData.schoolId = this.userInfo.studentInfo.school_id
      this.formData.schoolName = this.userInfo.studentInfo.school_name
      this.formData.studentId = this.userInfo.studentInfo.student_id
      this.formData.name = this.userInfo.studentInfo.name
      this.formData.idCard = this.userInfo.studentInfo.id_card
    }
  },
  methods: {
    // 设置表单验证规则
    setRules() {
      this.$refs.uForm.setRules(this.rules)
    },
    
    // 获取学校列表
    async getSchools() {
      try {
        const res = await this.$api.getSchools()
        if (res.data && res.data.code === 200) {
          const schools = res.data.data || []
          this.schoolOptions = schools.map(item => ({
            text: item.name,
            value: item.id
          }))
        }
      } catch (error) {
        console.error('获取学校列表失败', error)
        uni.showToast({
          title: '获取学校列表失败',
          icon: 'none'
        })
      }
    },
    
    // 确认选择学校
    confirmSchool(e) {
      const school = this.schoolOptions[e.indexs[0]]
      this.formData.schoolId = school.value
      this.formData.schoolName = school.text
      this.showSchoolPicker = false
    },
    
    // 提交表单
    submit() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.bindStudent()
        }
      })
    },
    
    // 绑定学生信息
    async bindStudent() {
      try {
        uni.showLoading({
          title: '提交中'
        })
        
        const res = await this.$api.bindStudent({
          school_id: this.formData.schoolId,
          student_id: this.formData.studentId,
          name: this.formData.name,
          id_card: this.formData.idCard
        })
        
        uni.hideLoading()
        
        if (res.data && res.data.code === 200) {
          uni.showToast({
            title: '绑定成功',
            icon: 'success'
          })
          
          // 更新用户信息
          this.$store.dispatch('getUserInfo')
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.data.message || '绑定失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('绑定学生信息失败', error)
        uni.showToast({
          title: '绑定失败，请稍后重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.form-section {
  background-color: #ffffff;
  padding: 20rpx;
  margin-top: 20rpx;
}

.input-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70rpx;
  
  .placeholder {
    color: #999;
  }
}

.tips {
  padding: 30rpx 20rpx;
  font-size: 24rpx;
  color: #999;
}

.submit-btn {
  padding: 40rpx 20rpx;
}
</style>
